package com.aldobucchi.mouse
{
	import com.aldobucchi.utils.App;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	
	public class MouseDragOffLimitsMonitor extends MouseTrackerBase
	{
		
		
		public function MouseDragOffLimitsMonitor( )
		{
			App.app.addEventListener( Event.ENTER_FRAME, app_enterFrame );
		}
		
		
		private function app_enterFrame( event:Event ):void
		{
			
			if ( ! enabled )
				return;
			
			if ( target == null )
				return;
				
			if ( target.width == 0 || target.height == 0 )
				return;
			
			var gaps:Array = calculateGaps( );
			if ( gaps.every( isZero ) )
				return;
				
			
			// we need to balance the gaps... 
			var correctionX:Number = gaps[1] - gaps[3];			
			var correctionY:Number = gaps[2] - gaps[0];

			
			if ( Math.abs( correctionX ) > 2 )
				target.x += correctionX/10;
			
			if ( Math.abs( correctionY ) > 2 )
				target.y += correctionY/10;
			
		
		}
		
		private function isZero( item:*, index:int, array:Array ):Boolean
		{
			return item == 0;
		}
		
		
		private function getCorrection( gap1:Number, gap2:Number ):Number
		{
			return gap2 - gap1;
		}
		
		
		private function calculateGaps( ):Array
		{
			var p:DisplayObject = target.parent;

			// we only allow whitespace when it is equally distributed at both sides
			var leftGap	:Number = target.x;
			var topGap	:Number = target.y;
			
			var rightGap	:Number = p.width - (target.x + target.width*target.scaleX);
			var bottomGap	:Number = p.height - (target.y + target.height*target.scaleY);

			return 	[ 
					topGap 		< 0 ? 0 : topGap, 
					rightGap 	< 0 ? 0 : rightGap, 
					bottomGap 	< 0 ? 0 : bottomGap, 
					leftGap 	< 0 ? 0 : leftGap 
				];
		
		}
		
	}
	
}